package com.redwine.app;

import android.text.TextUtils;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.MultipartRequest;
import com.redwine.app.net.responses.UploadImagesResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 上传图片
 * 作者：gassion on 17/9/12 12:37
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class UploadHelper {

    private List<UploadImagesResponse.DataEntity> mDatas;
    private int fileIndex = 0;
    private static final String ERROR_CODE = "501";
    private static final String EXIST_CODE = "502";
    private StringBuilder stringBuilder = new StringBuilder();

    public UploadHelper(List<UploadImagesResponse.DataEntity> datas) {
        this.mDatas = datas;
    }


    private String nextUploadFile() {
        if (fileIndex == -1 || mDatas == null || mDatas.size() == 0 || fileIndex >= mDatas.size()) {
            return ERROR_CODE;
        } else if (!TextUtils.isEmpty(mDatas.get(fileIndex).getLocalPath())) {
            String localPath = mDatas.get(fileIndex).getLocalPath();
            fileIndex++;
            return localPath;
        } else {
            if (!TextUtils.isEmpty(mDatas.get(fileIndex).getReal_url()))
                stringBuilder.append(mDatas.get(fileIndex).getReal_url() + ",");
            fileIndex++;
            return EXIST_CODE;
        }
    }

    private void didUpload(UploadImagesResponse.DataEntity data) {
        stringBuilder.append(data.getReal_url() + ",");
    }


    /**
     * 处理上传逻辑
     */
    public void uploadFile(final UploadListener uploadListener) {
        final String file = nextUploadFile();
        if (ERROR_CODE.equals(file)) {
            final String string = stringBuilder.toString();
            String substring = string.substring(0, string.length() - 1);
            uploadListener.onUploadComplete(true, substring);
        } else if (EXIST_CODE.equals(file)) {
            uploadFile(uploadListener);
        } else {
            String url = NetworkConstants.DELETE_UPLOAD_PIC_URL;
            Map<String, String> params = new LinkedHashMap<>();
            List<File> files = new ArrayList<>();
            files.add(new File(file));
            MultipartRequest<UploadImagesResponse> multipartRequest = new MultipartRequest<>(url, UploadImagesResponse.class, "images", files, params,
                    new Response.Listener<UploadImagesResponse>() {
                        @Override
                        public void onResponse(UploadImagesResponse response) {
                            if (response.isSuccess()) {
                                didUpload(response.getData());
                                uploadFile(uploadListener);
                            } else {
                                uploadListener.onUploadComplete(false, null);
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    uploadListener.onUploadComplete(false, null);
                }
            });
            multipartRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 60 * 1000,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            APP.getInstance().getRequestQueue().add(multipartRequest);
        }

    }

    public interface UploadListener {
        void onUploadComplete(boolean isSuccess, String string);
    }
}
